<?php

/**
 * Created by PhpStorm.
 * User: lian
 * Date: 17/9/23
 * Time: 上午10:44
 */
require_once dirname(__FILE__). '/../Requests/library/Requests.php'; //dirname(__FILE__)获取OneNet.php所在的目录
require_once dirname(__FILE__). '/../OneNet/config.php';
Requests::register_autoloader();
class OneNet
{
    /**
     * 批量查询设备状态
     * @param $idArray
     * @return
     * "devices": [
        {
        "id": 12323,//设备id
        "title": "daf",//设备名
        "online": false//设备在线状态，true为在线，false为离线
        },
        {
        …
        },
        …
        ]
     */
    public function getDevicesStatus($idArray) {
        $url = MB_API_HOST."devices/status?devIds=";
        $headers = array("api-key"=>MB_API_KEY);
        for ($i = 0; $i < count($idArray); $i++) {
            $url = $url . $idArray[$i];
            if ($i != count($idArray) - 1) {
                $url .= ",";
            }
        }
        $res = Requests::get($url, $headers);
//        var_dump($res);
//        Log::write("get device status Response:" . $res->body);
        $json = json_decode($res->body, true);
        if ($json["errno"] == 0) {
            return $json["data"]["devices"];
        } else {
            return null;
        }
    }

    /**
     * 获取多个设备数据
     * @param $deviceId
     * @param $dataStreamIds : array
     * @return
     * [

        "id":"temperature",    //数据流名称，设备范围内唯一

        "tags":["Tag1","Tag2"],//数据流标签

        "unit":"celsius",//单位

        "unit_symbol":"C",//单位符号

        "create_time":"xxxx-xx-xx 10:22:22",//创建时间

        "current_value":{…},//该数据流下数据点最新值

        "update_at":"xx-xx-xx"//该数据流下数据点最新上传时间

        ],

        [

        "id":"humi",    //数据流名称，设备范围内唯一

        "tags":["Tag1","Tag2"],

        "unit_symbol":"%",

        "create_time":"xxxx-xx-xx 10:22:22",

        "current_value":{…},

        "update_at":"xx-xx-xx"

        ],

        [...]

        }
     */
    public function getDeviceData($deviceId, $dataStreamIds) {
        $url = MB_API_HOST . "devices/" .$deviceId. "/datastreams?datastream_ids=";
        $headers = array("api-key"=>MB_API_KEY);
        for ($i = 0; $i < count($dataStreamIds); $i++) {
            $url .= $dataStreamIds[$i];
            if ($i != count($dataStreamIds) -1) {
                $url .= ",";
            }
        }
        $res = Requests::get($url, $headers);
        $json = json_decode($res->body, true);
        if ($json["errno"] == 0) {
            return $json["data"];
        } else {
            return null;
        }
    }

    /**
     * @param $deviceIds
     * @return
     *
     * [
        {
        "id": 12323, //设备id

        "title": "daf",//设备名

        " datastreams ": [
            {
            "id": "temperature",//数据流名称

            "at": "2017-02-12 10:22:22",//数据流更新时间

            "value": 12//数据流最新数据

            },

            {
            …..
            },
            ……
            ]
        },
        {
        …..
        },
        …..
        ]
     */
    public function getDevicesData($deviceIds) {
        $url = MB_API_HOST . "devices/datapoints?devIds=";
        $headers = array("api-key"=>MB_API_KEY);
        for ($i = 0; $i < count($deviceIds); $i++) {
            $url .= $deviceIds[$i];
            if ($i != count($deviceIds) -1) {
                $url .= ",";
            }
        }
//        var_dump($url);
        $res = Requests::get($url, $headers);
        $json = json_decode($res->body, true);
        if ($json["errno"] == 0) {
            return $json["data"]["devices"];
        } else {
            return null;
        }
        return null;
    }


    /**
     * @param $deviceId
     * @param $command
     * @return cmd_uuid 命令id,用于查询命令状态
     */
    public function sendCommand($deviceId, $command)
    {

        $url = MB_API_HOST . "cmds?device_id=" . $deviceId . "&qos=1&timeout=60";
        $headers = array('Content-Type' => 'application/json', "api-key" => MB_API_KEY);
        $data = $command;
        $res = Requests::post($url, $headers, json_encode($data));
//        Log::write("send commmad Response:" . $res->body);
        $json = json_decode($res->body, true);
        if ($json["errno"] == 0) {
            return $json["data"]["cmd_uuid"];
        } else {
            return null;
        }

    }

    /**
     * 查询命令状态
     * @param $cmdUuid
     * @return
     *  "data":{

            "status":1

            0：设备不在线|Device not   online

            1：命令已创建| Command   Created

            2：命令已发往设备| Command Sent

            3：命令发往设备失败| Send Command Failed

            4：设备正常响应| Command Response Received

            5：命令执行超时| Command Response Timeout

            6：设备响应消息过长 | Command   Response Too Large

            "desc":“sending”

            }
     */
    public function getCommandStatus($cmdUuid) {
        $url = MB_API_HOST . "cmds/".$cmdUuid;
        $headers = array("api-key"=>MB_API_KEY);
        $res = Requests::get($url, $headers);
//        Log::write("get commmad status Response:" . $res->body);
//        var_dump("uuid:".$cmdUuid);
//        var_dump($res);
        $json = json_decode($res->body, true);
        if ($json["errno"] == 0) {
            return $json["data"];
        } else {
            return null;
        }
    }

    /**
     * @param $imei
     * @return
     * {

        "key":"Q1VdWoEvdkCye=d1=HcCSP6LvCw=",  //设备apikey

        "device_id": 325018,   //设备ID

        }
     */
    public function registerDevice($imei) {
        $url = MB_API_HOST."register_de?register_code="."3grdWomEixiIp0Px";
        $headers = array("api-key"=>MB_API_KEY);
        $res = Requests::post($url, $headers, json_encode(array("sn"=>$imei, "title"=>"device_".$imei)));
        //var_dump($res);
        $json = json_decode($res->body, true);
        if ($json["errno"] == 0) {
            return $json["data"];
        } else {
            return null;
        }
    }

    public function checkAck($cmdUuid) {
        $checkRes = $this->getCommandStatus($cmdUuid);
//        var_dump($checkRes);
        if ($checkRes != null) {
            if ($checkRes["status"] == 4) {
                M("yichong_charge")->where(array("cmd_uuid"=>$cmdUuid))->save(array("has_execute"=>1));
            }
            echo json_encode(array("status"=>$checkRes["status"]));
        } else {
            echo json_encode(array("status"=>7)); //请求失败
        }
    }
}